package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //1.根据username调用mapper进行查询
        Employee employee = employeeMapper.login(username);
        if (employee == null) {
            return ResultInfo.error("该用户不存在");
        }
        //2.将传入的password进行加密 然后与数据库中的密码进行对比
        //SecureUtil.md5 加密字符串
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5, employee.getPassword())) {
            return ResultInfo.error("密码错误!");
        }
        //3.查询到用户的status是否是1(激活)如果不是 说明当前该用户的状态不允许登录
        Integer status = employee.getStatus();
        if (status == employee.STATUS_DISABLE) {
            return ResultInfo.error("用户状态错误!");
        }
        //4.三个条件都对.表示登录成功,返回成功标识
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) {
        //1.补齐参数
        employee.setPassword(SecureUtil.md5("123"));//设置密码默认是123 加密
        employee.setStatus(Employee.STATUS_ENABLE);//状态默认是1
        employeeMapper.insert(employee);
    }

    @Override
    public Employee findByID(Long id) {
        return employeeMapper.findByiD(id);
    }

    @Override
    public void update(Employee employee) {
        employeeMapper.updateById(employee);

    }
}
